package billing.inf.redis;

import javax.annotation.PostConstruct;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.ShardedJedisPool;
import billing.inf.helps.ObjectHelp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class RedisClient {
	private JedisPool jedisPool;
	private ShardedJedisPool shardedJedisPool;
	
	public void setJedisPool(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}
	public void setShardedJedisPool(ShardedJedisPool shardedJedisPool) {
		this.shardedJedisPool = shardedJedisPool;
	}

	/** 操作Key的方法 */
	public Keys KEYS;
	/** 对存储结构为String类型的操作 */
	public Strings STRINGS;
	/** 对存储结构为List类型的操作 */
	public Lists LISTS;
	/** 对存储结构为Set类型的操作 */
	public Sets SETS;
	/** 对存储结构为HashMap类型的操作 */
	public Hash HASH;
	/** 对存储结构为Set(排序的)类型的操作 */
	public SortSet SORTSET;

	@PostConstruct
	public void init() {
		KEYS = new Keys(shardedJedisPool,jedisPool);
		STRINGS = new Strings(shardedJedisPool,jedisPool);
		LISTS = new Lists(shardedJedisPool,jedisPool);
		SETS = new Sets(shardedJedisPool,jedisPool);
		SORTSET = new SortSet(shardedJedisPool,jedisPool);
		HASH = new Hash(shardedJedisPool,jedisPool);
	}
	
	protected static String object2String(Object object) {
		String json = "";
		if(!ObjectHelp.isEmpty(object)){
			json = JSON.toJSONString(object,SerializerFeature.WriteClassName);
		}
		return json;
	}

	@SuppressWarnings("all")
	protected static <T> T string2Object(String json) {
		T result = (T) JSON.parse(json);
		return result;
	}
	
	public void add2SubListener(SubListener listener) {
		Jedis jedis=jedisPool.getResource();
		jedis.psubscribe(listener,listener.getPatterns());
		jedisPool.returnResource(jedis);
	}
	
	public void publish(String channel, Object value) {
		Jedis jedis=jedisPool.getResource();
		jedis.publish(channel, object2String(value));
		jedisPool.returnResource(jedis);
	}
}
